package com.xwj.controller;

import com.xwj.common.dto.BaseResponse;
import com.xwj.dto.UserAccountDto;
import com.xwj.service.DataBaseLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 使用数据库乐观锁、悲观锁实现银行账户提现高并发测试
 *
 * @author xwj
 * @date 2020/4/29
 */
@RestController
@RequestMapping("/database/lock/")
public class DataBaseLockController {
    @Autowired
    private DataBaseLockService dataBaseLockService;

    /**
     * 无锁
     * @param dto
     * @return
     */
    @GetMapping("/takeMoneyNoLock")
    public BaseResponse takeMoneyNoLock(@Validated UserAccountDto dto) {
        try {
            dataBaseLockService.takeMoneyNoLock(dto);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error(e.getMessage());
        }
    }

    /**
     * 乐观锁
     * @param dto
     * @return
     */
    @GetMapping("/takeMoneyOptimisticLock")
    public BaseResponse takeMoneyOptimisticLock(@Validated UserAccountDto dto) {
        try {
            dataBaseLockService.takeMoneyOptimisticLock(dto);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error(e.getMessage());
        }
    }

    /**
     * 悲观锁
     * @param dto
     * @return
     */
    @GetMapping("/takeMoneyPessimisticLock")
    public BaseResponse takeMoneyPessimisticLock(@Validated UserAccountDto dto) {
        try {
            dataBaseLockService.takeMoneyPessimisticLock(dto);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error(e.getMessage());
        }
    }
}
